#!/bin/bash
# ERP Mock Server 一键部署脚本
# 适用于腾讯云Ubuntu 20.04+服务器

set -e  # 遇到错误立即退出

# 配置变量
# 优先从 .env 加载 APP_DIR，未设置则默认 /opt/erp-mock
ENV_FILE="/opt/erp-mock/.env"
if [ -f "$ENV_FILE" ]; then
    set -a && . "$ENV_FILE" && set +a
fi
APP_DIR="${APP_DIR:-/opt/erp-mock}"
APP_PORT=3003
NGINX_PORT=8082
USER="www-data"

echo "========================================"
echo "ERP Mock Server 部署脚本"
echo "========================================"

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "请使用sudo运行此脚本"
    exit 1
fi

# 1. 检查必要的软件
echo ""
echo "[1/8] 检查系统环境..."
command -v python3 >/dev/null 2>&1 || { echo "Python3未安装"; exit 1; }
command -v pip3 >/dev/null 2>&1 || { echo "pip3未安装"; exit 1; }
command -v supervisorctl >/dev/null 2>&1 || { echo "Supervisor未安装"; exit 1; }
command -v nginx >/dev/null 2>&1 || { echo "Nginx未安装"; exit 1; }
echo "✓ 系统环境检查通过"

# 2. 创建应用目录
echo ""
echo "[2/8] 创建应用目录..."
if [ ! -d "$APP_DIR" ]; then
    echo "请先将代码放置到 $APP_DIR 目录"
    exit 1
fi
echo "✓ 应用目录: $APP_DIR"

# 3. 创建Python虚拟环境
echo ""
echo "[3/8] 创建Python虚拟环境..."
cd $APP_DIR
if [ ! -d "venv" ]; then
    python3 -m venv venv
    echo "✓ 虚拟环境创建成功"
else
    echo "✓ 虚拟环境已存在"
fi

# 4. 安装Python依赖
echo ""
echo "[4/8] 安装Python依赖..."
source venv/bin/activate
pip install --upgrade pip -q
pip install -r requirements.txt -q
echo "✓ Python依赖安装完成"

# 5. 创建日志目录
echo ""
echo "[5/8] 创建日志目录..."
mkdir -p $APP_DIR/logs
chown -R $USER:$USER $APP_DIR/logs
chmod 755 $APP_DIR/logs
echo "✓ 日志目录创建完成"

# 6. 配置Supervisor
echo ""
echo "[6/8] 配置Supervisor..."
cat > /etc/supervisor/conf.d/erp-mock.conf << EOF
[program:erp-mock]
command=$APP_DIR/venv/bin/python $APP_DIR/main.py
directory=$APP_DIR
user=$USER
autostart=true
autorestart=true
startretries=3
redirect_stderr=true
stdout_logfile=$APP_DIR/logs/supervisor.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=10
stderr_logfile=$APP_DIR/logs/supervisor_error.log
stderr_logfile_maxbytes=10MB
stderr_logfile_backups=10
environment=PYTHONUNBUFFERED="1",FLASK_ENV="production",FLASK_CONFIG="production",HOST="127.0.0.1",PORT="$APP_PORT"
stopsignal=TERM
stopwaitsecs=10
EOF

supervisorctl reread
supervisorctl update
supervisorctl restart erp-mock
echo "✓ Supervisor配置完成"

# 7. 配置Nginx
echo ""
echo "[7/8] 配置Nginx..."
cat > /etc/nginx/sites-available/erp-mock << EOF
upstream erp_mock_backend {
    server 127.0.0.1:$APP_PORT fail_timeout=0;
}

server {
    listen $NGINX_PORT;
    server_name _;

    access_log /var/log/nginx/erp-mock-access.log;
    error_log /var/log/nginx/erp-mock-error.log;

    client_max_body_size 10M;

    location /static/ {
        alias $APP_DIR/static/;
        expires 30d;
        access_log off;
    }

    location / {
        proxy_pass http://erp_mock_backend;
        proxy_redirect off;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    location /health {
        proxy_pass http://erp_mock_backend;
        access_log off;
    }
}
EOF

# 启用站点配置
ln -sf /etc/nginx/sites-available/erp-mock /etc/nginx/sites-enabled/

# 测试Nginx配置
nginx -t

# 重启Nginx
systemctl restart nginx
echo "✓ Nginx配置完成"

# 8. 验证部署
echo ""
echo "[8/8] 验证部署..."
sleep 3

# 检查应用状态
if supervisorctl status erp-mock | grep -q RUNNING; then
    echo "✓ 应用服务运行正常"
else
    echo "✗ 应用服务启动失败"
    supervisorctl tail erp-mock
    exit 1
fi

# 检查健康检查
if curl -s http://127.0.0.1:$APP_PORT/health > /dev/null; then
    echo "✓ 应用健康检查通过"
else
    echo "✗ 应用健康检查失败"
    exit 1
fi

# 检查Nginx代理
if curl -s http://127.0.0.1:$NGINX_PORT/health > /dev/null; then
    echo "✓ Nginx代理正常"
else
    echo "✗ Nginx代理失败"
    exit 1
fi

# 完成
echo ""
echo "========================================"
echo "✓ 部署完成！"
echo "========================================"
echo ""
echo "访问地址："
echo "  健康检查: http://$(hostname -I | awk '{print $1}'):$NGINX_PORT/health"
echo "  管理后台: http://$(hostname -I | awk '{print $1}'):$NGINX_PORT/static/admin.html"
echo ""
echo "常用命令："
echo "  查看状态: sudo supervisorctl status erp-mock"
echo "  重启服务: sudo supervisorctl restart erp-mock"
echo "  查看日志: tail -f $APP_DIR/logs/erp_mock.log"
echo ""
echo "注意事项："
echo "  1. 请在腾讯云安全组开放 $NGINX_PORT 端口"
echo "  2. 建议修改 config.py 中的认证密钥"
echo "  3. 建议配置日志清理和备份任务"
echo ""
